<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>蓝猫 - 现代购物体验</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <div class="logo">蓝猫</div>
        <nav>
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="cart.html">Cart</a></li>
                <li id="auth-links">
                    <a href="login.html">Login</a>
                    <a href="register.html">Register</a>
                </li>
                <li id="user-info" class="hidden"></li>
            </ul>
        </nav>
    </header>

    <div class="container">
        <h1>购物车</h1>
        <div class="cart-items" id="cart-container">
            <!-- Cart items will be loaded here -->
        </div>
    </div>

    <script>
        let currentUser = null;
        let accessToken = localStorage.getItem('access_token');

        async function checkAuth() {
            if (accessToken) {
                try {
                    const response = await fetch('http://192.168.10.124:8000/me', {
                        headers: {
                            'Authorization': `Bearer ${accessToken}`
                        }
                    });
                    if (response.ok) {
                        currentUser = await response.json();
                        document.getElementById('auth-links').classList.add('hidden');
                        document.getElementById('user-info').classList.remove('hidden');
                        document.getElementById('user-info').innerHTML = `
                            <div class="user-info">
                                <span>Hello, ${currentUser.username}!</span>
                            </div>
                        `;
                        loadCart();
                        return true;
                    } else {
                        logout();
                        return false;
                    }
                } catch (error) {
                    logout();
                    return false;
                }
            }
            return false;
        }

        async function loadCart() {
            try {
                const response = await fetch('http://192.168.10.124:8000/cart/', {
                    headers: {
                        'Authorization': `Bearer ${accessToken}`
                    }
                });
                
                if (response.ok) {
                    const cartItems = await response.json();
                    const container = document.getElementById('cart-container');
                    
                    if (cartItems.length === 0) {
                        container.innerHTML = '<p>Your cart is empty. <a href="index.html">Continue shopping</a></p>';
                        return;
                    }
                    
                    let total = 0;
                    const itemsHtml = cartItems.map(item => {
                        const itemTotal = item.product.price * item.quantity;
                        total += itemTotal;
                        return `
                            <div class="cart-item">
                                <div>
                                    <h3>${item.product.name}</h3>
                                    <p>$${item.product.price.toFixed(2)} × ${item.quantity}</p>
                                </div>
                                <div>
                                    <p>$${itemTotal.toFixed(2)}</p>
                                    <button class="btn btn-danger" onclick="removeFromCart(${item.id})">Remove</button>
                                </div>
                            </div>
                        `;
                    }).join('');
                    
                    container.innerHTML = `
                        ${itemsHtml}
                        <div class="cart-total">Total: $${total.toFixed(2)}</div>
                        <button class="btn btn-primary" style="margin-top: 1rem; width: 100%;">Checkout</button>
                    `;
                } else {
                    container.innerHTML = '<p>Error loading cart. Please login again.</p>';
                }
            } catch (error) {
                console.error('Error loading cart:', error);
                document.getElementById('cart-container').innerHTML = '<p>Error loading cart. Please try again.</p>';
            }
        }

        async function removeFromCart(cartItemId) {
            if (!confirm('Are you sure you want to remove this item from your cart?')) {
                return;
            }
            
            try {
                const response = await fetch(`http://192.168.10.124:8000/cart/${cartItemId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${accessToken}`
                    }
                });
                
                if (response.ok) {
                    loadCart();
                } else {
                    alert('Error removing item from cart');
                }
            } catch (error) {
                console.error('Error removing from cart:', error);
                alert('Error removing item from cart. Please try again.');
            }
        }

        function logout() {
            localStorage.removeItem('access_token');
            currentUser = null;
            accessToken = null;
            document.getElementById('auth-links').classList.remove('hidden');
            document.getElementById('user-info').classList.add('hidden');
            document.getElementById('cart-container').innerHTML = '<p>Please login to view your cart.</p>';
        }

        // Initialize
        checkAuth();
    </script>
</body>
</html>